<?php

namespace App\Http\Controllers;

use App\Exceptions\InvalidRequestException;
use App\Models\OrderItem;
use App\Models\Product;
use Illuminate\Http\Request;

class ProductsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        // product::query() 获取不用全局作用域的查询构建器
        $builder = Product::query()->where('on_sale', true);

        // 筛选维持
        if ($search = $request->input('search', '')) {
            $like = '%' . $search . '%';
            // 模糊搜索商品标题、商品详情、SKU 标题、SKU描述
            $builder->where(function ($query) use ($like) {
                $query->where('title', 'like', $like)
                    ->orWhere('description', 'like', $like)
                    ->orWhereHas('skus', function ($query) use ($like) {
                        // orWhereHas 判断是否存在对应的子关联关系，有则执行闭包，增加子构造器条件维持
                        $query->where('title', 'like', $like)
                            ->orWhere('description', 'like', $like);
                    });
            });
        }

        // 排序维持
        if ($order = $request->input('order', '')) {
            // 正则匹配升降序
            if (preg_match('/^(.+)_(asc|desc)$/', $order, $m)) {
                // 检测排序值是否合法
                if (in_array($m[1], ['price', 'sold_count', 'rating'])) {
                    // 构造排序参数,实现排序条件维持
                    $builder->orderBy($m[1], $m[2]);
                }
            }
        }

        // 分页对象
        $products = $builder->paginate(8);

        return view('products.index', [
            'products' => $products,
            'filters' => [
                'search' => $search,
                'order' => $order,
            ],
        ]);
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function show(Product $product, Request $request)
    {
        //判断商品是否已经上架，如果没有上架则抛出异常
        if (!$product->on_sale) {
            throw new InvalidRequestException('商品未上架');
        }

        $favored = false;
        // 用户未登录时返回的是null,已登录时返回的是对应的用户对象
        if ($user = $request->user()) {
            // boolval() 函数用于把值转为布尔值
            $favored = boolval($user->favoriteProducts()->find($product->id));
        }

        $reviews = OrderItem::query()
            ->with(['order.user', 'productSku']) // 预加载关联关系
            ->where('product_id', $product->id)
            ->whereNotNull('reviewed_at') //筛选出已评价的
            ->orderBy('reviewed_at', 'desc') // 按评价时间倒序
            ->limit(10) // 取出10条
            ->get();

        return view('products.show', [
            'product' => $product,
            'favored' => $favored,
            'reviews' => $reviews,
        ]);
    }

    /**
     * 收藏喜欢
     *
     * @param Product $product
     * @param Request $request
     * @return void
     */
    public function favor(Product $product, Request $request)
    {
        $user = $request->user();
        if ($user->favoriteProducts()->find($product->id)) {
            return [];
        }

        // 添加中间表数据记录， 多对多关系
        $user->favoriteProducts()->attach($product);

        return [];
    }

    /**
     * 取消点赞
     *
     * @param Product $product
     * @param Request $request
     * @return void
     */
    public function disfavor(Product $product, Request $request)
    {
        $user = $request->user();
        // 删除中间表数据记录
        $user->favoriteProducts()->detach($product);

        return [];
    }

    public function favorites(Request $request)
    {
        $products = $request->user()->favoriteProducts()->paginate(5);

        return view('products.favorites', ['products' => $products]);

    }

}
